package la.bbs558.aop.delay.handler;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import la.bbs558.aop.delay.DelayQueueManager;
import la.bbs558.aop.delay.DelayTask;
import la.bbs558.entity.BbsClass;
import la.bbs558.entity.BbsClassActive;
import la.bbs558.service.BbsClassService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.Serializable;

/**
 * @Classname DelayUserHandler
 * @Description TODO
 * @Date 2023/11/11 17:37
 * @Created by weihanmin
 */
@Component
@Slf4j
public class BbsClassActiveStartDelayHandler extends BbsClassActiveDelayHandler {
    @Resource
    private BbsClassService bbsClassService;
    @Override
    public void doHandle(DelayTask<?> delayTask, DelayQueueManager delayQueueManager) {
        Serializable entity = delayTask.getEntity();
        if(entity instanceof BbsClass){
            BbsClassActiveContext activeContext = initCtx(((BbsClass) entity).getId());
            BbsClass bbsClass = activeContext.getBbsClass();
            BbsClassActive bbsClassActive = activeContext.getBbsClassActive();
            DateTime now = DateUtil.date();
            if(now.isBefore(bbsClassActive.getStartTime())){
                //扔回延时队列
                delayQueueManager.addTask(delayTask);
                return;
            }
            //设置主题活动为开始状态
            bbsClassActiveService.lambdaUpdate()
                    .eq(BbsClassActive::getId,bbsClassActive.getId())
                    .set(BbsClassActive::getStatus,1).update();
            bbsClassService.lambdaUpdate()
                    .eq(BbsClass::getId,bbsClass.getId())
                    .set(BbsClass::getStatus,1).update();
        }
    }
    @Override
    public void doHandleError(DelayTask<?> delayTask, DelayQueueManager delayQueueManager, Throwable e) {
        log.error("主题活动处理出现异常",e);
    }
}
